import axios from 'axios';
import { ElMessage } from 'element-plus'

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

const config = {
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
};

const _axios = axios.create(config);

_axios.interceptors.request.use(
  (cfg) => {
    if (cfg.url && cfg.url.indexOf('/shop/') == -1) {
      cfg.url = '/shop' + cfg.url;
    }
    return cfg;
  },
  (err) => {
    // Do something with request error
    return Promise.reject(err);
  },
);

// Add a response interceptor
_axios.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code !== 1) {
      ElMessage.error(res.msg === '' ? '服务器错误' : res.msg);
      return Promise.reject('error');
    } else {
      return res.result;
    }
  },
  (err) => {
    // Do something with response error
    return Promise.reject(err);
  },
);

export function request (params:any) {
  return _axios.request(params)
}

export default {
  install:function(app:any, options:any) {
    app.config.globalProperties.axios = _axios;
    // 添加全局的方法
    app.config.globalProperties.$translate = (key: any) => {
      // return key.split('.').reduce((o, i) => {
      //   if (o) return o[i]
      // }, i18n)
      return key
    }
  }
};
